const App = {
  mixins: [Save],//配置文件，路径/utils/mixins.js
  data() {
    return {
      Nation: [],
      Ducation: ducation(),
      village: [],
      cityValue: [],
      cityValue1: [],
      city: [],
      city1: [],
      personal_Image: '',
      Affiliation: [
        {
          value: "群众",
          label: "群众",
        },
        {
          value: "无党派人士",
          label: "无党派人士",
        },
        {
          value: "民主党派成员",
          label: "民主党派成员",
        },
        {
          value: "共青团员",
          label: "共青团员",
        },
        {
          value: "中共预备党员",
          label: "中共预备党员",
        },
        {
          value: "中共党员",
          label: "中共党员",
        },
      ],
    };
  },
  mounted() {
    this.getCategory();
    this.getCity();
    let ls_URL = window.location.href;
    const Personal_Resource = getQueryObject(ls_URL, "Personal_Resource");// 获取 nodeKey 参数
    if (Personal_Resource) {
      this.dataForm.Personal_Resource = Personal_Resource;
    }
    console.log(this.Ducation);
  },
  watch: {
    'dataForm.ID_Card_Number'(val) {
      if (this.action != 'Add') {
        this.cityValue = [this.dataForm.RR_Province_Number, this.dataForm.RR_City_Number, this.dataForm.RR_County_Nubmer];
        this.cityValue1 = [this.dataForm.RR_Town_Number, this.dataForm.RR_Village_Number];
        if (this.dataForm.RR_County_Nubmer) {
          $.ajax({
            headers: requestHeaders(),
            url: `${mh}/clientOperation/getDistrictTree`,
            type: "GET",
            data: {
              DistrictCode: this.dataForm.RR_County_Nubmer
            },
            success: (data) => {
              this.city1 = data[0].children;
            },
            complete: (XMLHttpRequest) => {
              requestPretreatment(XMLHttpRequest);
            },
            dataType: "json",
          });
        }
      }
    },
    personal_Image(val) {
      $.ajax({
        url: `${y}/parseIDCard`,
        type: "POST",
        data: {
          Data: val,
        },
        success: (res) => {
          if (res.Status == "success") {
            this.dataForm.ID_Card_Number = res.ID_Number;
            this.dataForm.Personal_Name = res.name;
            this.InputID_Card_Number(res.ID_Number)
          }
        },
        dataType: "json",
      });
    }
  },
  methods: {
    ID_Validity(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入身份证'));
      } else if (!ID_Validity(value)) {
        callback(new Error('身份证格式不正确'));
      } else {
        callback();
      }
    },
    PH_Validity(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入联系电话'));
      } else if (!validatemobile(value)) {
        callback(new Error('联系电话格式不正确'));
      } else {
        callback();
      }
    },
    // InputID_Card_Number(val) {
    //   if (ID_Validity(val)) {
    //     this.dataForm.Birthday = Return_BirthdayByID(val);
    //     this.dataForm.Gender = Return_SexByID(val);
    //     this.dataForm.Birthday = Return_BirthdayByID(val);
    //     // this.cityValue = [val.substring(0, 2)+'0000',val.substring(0, 4)+'00',val.substring(0, 6)]
    //   }
    // },
    changeCity1(val) {
      if (val.length > 0) {
        let Town = this.city1.filter(i => i.ProvinceNumber == val[0])[0];
        let Village = Town.children.filter(i => i.ProvinceNumber == val[1])[0];
        let arr = this.dataForm.Registered_Residence.split('/');
        this.dataForm.Registered_Residence = arr[0] + '/' + arr[1] + '/' + arr[2] + '/' + Town.Province + '/' + Village.Province;
        this.dataForm.RR_Town_Number = val[0];
        this.dataForm.RR_Village_Number = val[1];
      } else {
        this.dataForm.RR_Town_Number = '';
        this.dataForm.RR_Village_Number = '';
      }
    },
    changeCity(val) {
      console.log(val);
      if (val.length > 0) {
        let Province = this.city.filter(i => i.value == val[0])[0];
        let City = Province.children.filter(i => i.value == val[1])[0];
        let County = City.children.filter(i => i.value == val[2])[0];
        this.dataForm.Registered_Residence = Province.label + '/' + City.label + '/' + County.label;
        this.dataForm.RR_Province_Number = val[0];
        this.dataForm.RR_City_Number = val[1];
        this.dataForm.RR_County_Nubmer = val[2];
        this.dataForm.RR_Town_Number = '';
        this.dataForm.RR_Village_Number = '';
        this.cityValue1 = [];
        if (val.length > 0) {
          console.log(val[2]);
          $.ajax({
            headers: requestHeaders(),
            url: `${mh}/clientOperation/getDistrictTree`,
            type: "GET",
            data: {
              DistrictCode: val[2]
            },
            success: (data) => {
              this.city1 = data[0].children;
            },
            complete: (XMLHttpRequest) => {
              requestPretreatment(XMLHttpRequest);
            },
            dataType: "json",
          });
        }
      } else {
        this.dataForm.Registered_Residence = '';
        this.dataForm.RR_Province_Number = '';
        this.dataForm.RR_City_Number = '';
        this.dataForm.RR_County_Nubmer = '';
        this.dataForm.RR_Town_Number = '';
        this.dataForm.RR_Village_Number = '';
        this.cityValue1 = [];
      }
    },
    getCity() {
      $.ajax({
        url: `${absolutepath()}api/Districtjl.json`,
        method: "get",
        success: (data) => {
          data.forEach(item => {
            item.children.forEach(ite => {
              ite.children.forEach(it => {
                it.children = undefined
              })
            })
          })
          this.city = data;
          if (this.action == 'Add') {
            this.cityValue = ['230000', '232700', '232723']
            this.changeCity(this.cityValue)
          }

        },

      });
    },
    getCategory() {
      $.ajax({
        url: absolutepath() + "api/Nation.json",
        type: "GET",
        success: (data) => {
          this.Nation = data;
        },
        dataType: "json",
      });
    },
    // changeCity(val) {
    //   if (val.length > 0) {
    //     let Province = this.city.filter(i => i.value == val[0])[0];
    //     let City = Province.children.filter(i => i.value == val[1])[0];
    //     let County = City.children.filter(i => i.value == val[2])[0];
    //     let Town = County.children.filter(i => i.value == val[3])[0];
    //     this.dataForm.Registered_Residence = Province.label + City.label + County.label + Town.label;
    //     this.dataForm.RR_Province_Number = val[0];
    //     this.dataForm.RR_City_Number = val[1];
    //     this.dataForm.RR_County_Nubmer = val[2];
    //     this.dataForm.RR_Town_Number = val[3];
    //     //   $.ajax({
    //     //     url: `${mh}/generalBusiness/generalQueryByTableName`,
    //     //     type: "POST",
    //     //     data: {
    //     //         Data: 'base_system_village',
    //     //         Condition: "TownNumber = '"+val[3]+"'",
    //     //     },
    //     //     success: (data) => {
    //     //         this.village = data; // 直接使用 this
    //     //     },
    //     //     dataType: "json",
    //     // });
    //   } else {
    //     this.dataForm.Registered_Residence = '';
    //     this.dataForm.RR_Province_Number = '';
    //     this.dataForm.RR_City_Number = '';
    //     this.dataForm.RR_County_Nubmer = '';
    //     this.dataForm.RR_Town_Number = '';
    //   }
    // },
    handleChange(file, fileList) {
      const reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = () => {
        const base64Data = reader.result;
        console.log("Base64 编码的图片数据：", base64Data);
        const parts = base64Data.split("base64,");
        if (parts.length > 1) {
          var extractedData = parts[1];
          console.log(extractedData); //想要的数据
        } else {
          console.log("未找到 Base64 数据");
        }
        // return
        const _this = this;
        $.ajax({
          headers: {
            "content-type": "application/json",
          },
          url: `${mh}/clientOperation/parseIDCard`,
          method: "post",
          data: extractedData,
          success: (res) => {
            console.log(res);
            console.log(res.words_result[0].card_result);
            _this.personal_information.ID_Card_Number =
              res.words_result[0].card_result.公民身份号码.words;
            _this.personal_information.Personal_Name =
              res.words_result[0].card_result.姓名.words;
            _this.personal_information.Gender =
              res.words_result[0].card_result.性别.words;
            _this.personal_information.Registered_Residence =
              res.words_result[0].card_result.住址.words;
            _this.personal_information.Nation =
              res.words_result[0].card_result.民族.words;
            const birthStr = res.words_result[0].card_result.出生.words;
            if (birthStr.length === 8) {
              const formattedBirthday = `${birthStr.slice(
                0,
                4
              )}-${birthStr.slice(4, 6)}-${birthStr.slice(6)}`;
              _this.personal_information.Birthday = formattedBirthday;
            } else {
              console.log("出生日期格式不正确，应为 8 位数字");
            }
          },
          error: (err) => {
            console.log(err);
          },
        });
      };
      reader.onerror = () => {
        console.error("读取文件时出错");
      };
    },
    Success(res) {
      console.log(res);
    },
    async handleSubmit() {
      const allValid = await this.validateAllForms();
      if (allValid) {
        this.loading = true;
        let ls_URL = window.location.href;
        const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
        let lJSONObject_Data_Options = new Object();
        lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

        let ls_MainTableName = lJSONObject_Data_Options.TableName;
        let ls_DataForm = lJSONObject_Data_Options.form;
        let ls_primary_key = lJSONObject_Data_Options.primary_key;
        //没有子表下面内容就会报错，try/catch抛出异常
        try {
          //可能涉及多个子表
          document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
            let lJSONObject_ChildData_Options = new Object();
            lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

            let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
            let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
            // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
            if (this[ls_DataForm][ls_primary_key]) {
              this[ls_ChildDataForm].forEach(item => {
                item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
              })
            }
            //建立子表结构体
            let JSONArray_ChildRecord = new Array();
            JSONArray_ChildRecord = this[ls_ChildDataForm];
            if (!this[ls_DataForm].Children) {
              this[ls_DataForm].Children = new Object();
            }
            this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
          })
        } catch (error) {

        }
        // if (this[ls_DataForm].RR_County_Nubmer == '232723') {
        this[ls_DataForm].Migrant_Personal = (this[ls_DataForm].RR_County_Nubmer == '232723' ? '0' : '1')
        // }
        //建立新增提交结构
        let lJSONObject_DataSet = new Object();
        if (action == 'Add') {
          $.ajax({
            headers: requestHeaders(),
            url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
            method: "post",
            data: {
              Data: 'personal_information',
              Condition: `ID_Card_Number='${this[ls_DataForm].ID_Card_Number}' AND Row_Status='1'`,
            },
            success: (data) => {
              if (data.length == 1) {
                for (let key in data[0]) {
                  if (!key.includes('_Original') && !key.includes('Operation_ID') && !key.includes('Operation_Datetime') && !key.includes('Create_Datetime') && !key.includes('Creater_SerialNumber')) {
                    data[0][key] = (key == 'Row_Status' ? '0' : '')
                  } else if (key == 'Create_Datetime') {
                    data[0][key] = getYMDHMSDate() + '.' + data[0][key].split('.')[1]
                  }
                }
                let obj = { ...data[0], ...this[ls_DataForm] };
                lJSONObject_DataSet = {
                  Modify: {
                    personal_information: [obj]
                  },
                  Add: {
                    personal_Contact_Phone: [{ Contact_Phone: this[ls_DataForm].Contact_Phone }]
                  }
                }
              } else {
                if (this.nodeKey) {
                  this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
                }
                let lJSONArray_Record = new Array();
                lJSONArray_Record.push(this[ls_DataForm]);
                let lJSONObject_Table = new Object();
                lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                lJSONObject_Table['personal_Contact_Phone'] = [{ Contact_Phone: this[ls_DataForm].Contact_Phone }];
                lJSONObject_DataSet[action] = lJSONObject_Table;
              }
              let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
              if (!lJSONObject_DataSet['Add']) {
                lJSONObject_DataSet['Add'] = new Object();
              }
              lJSONObject_DataSet['Add']['base_operation_log'] = [{
                Operation_Type: '0',
                Operation_Path: this.relativePath,
                Operation_Main,
                Operation_Interface: "generalSave",
                Operation_IP: getIpAddress()
              }]
              submitSave(lJSONObject_DataSet, (res) => {
                if (res.Status == 'success') {
                  window.location.href = './personal.html'
                }
                this.loading = false;
              })
            },
            complete: (XMLHttpRequest) => {
              requestPretreatment(XMLHttpRequest)
            },
          });
        } else if (action == 'Modify') {
          this[ls_DataForm].Children.personal_education_status.forEach(item => {
            item.ID_Card_Number = this[ls_DataForm].ID_Card_Number
          })
          const { add, modify } = this.deal(this[ls_DataForm]);
          let lJSONArray_Record = new Array();
          lJSONArray_Record.push(modify);

          let lJSONObject_Table = new Object();
          lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

          lJSONObject_DataSet[action] = lJSONObject_Table;
          if (add != null) {
            let lJSONArray_Record_Add = new Array();
            lJSONArray_Record_Add.push(add);

            let lJSONObject_Table_Add = new Object();
            lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

            lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
          }
          let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
          if (!lJSONObject_DataSet['Add']) {
            lJSONObject_DataSet['Add'] = new Object();
          }
          lJSONObject_DataSet['Add']['base_operation_log'] = [{
            Operation_Type: '0',
            Operation_Path: this.relativePath,
            Operation_Main,
            Operation_Interface: "generalSave",
            Operation_IP: getIpAddress()
          }]
          submitSave(lJSONObject_DataSet, (res) => {
            if (res.Status == 'success') {
              window.location.href = './personal.html'
            }
            this.loading = false;
          })
        }

        // $.ajax({
        //   headers: requestHeaders(),
        //   url: `${mh}/generalBusiness/generalSave`,
        //   method: "post",
        //   data: {
        //     Data: JSON.stringify(lJSONObject_DataSet),
        //   },
        //   success: (res) => {
        //     if (res.Status == 'success') {
        //       window.location.href = './personal.html'
        //     }
        //   },
        //   complete: (XMLHttpRequest) => {
        //     requestPretreatment(XMLHttpRequest);
        //     this.loading = false;
        // },
        // });
      }
    },
  },
};

const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
app.component('yl-upload', ylUpload);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
